﻿//
// Created by QU on 24-9-23.
//

#ifndef BASENODE_H
#define BASENODE_H

#include <memory>
#include <limits>
#include <ostream>
#include <boost/endian/conversion.hpp>

class BaseNode
{
public:
    struct SerializedData {
        std::unique_ptr<std::byte[]> buffer;
        uint16_t length;
    };

    // 这里有又是一个坑, 因为16位能表示的最大值为65535,
    // 我为了测试最大PAYLOAD, 将65535直接赋值了, 在计算总大小的时候, 65535 + 4(Header)导致溢出, 进而收到的字节数始终不对.
    constexpr static uint16_t MAX_NODE_SIZE = std::numeric_limits<uint16_t>::max();
    constexpr static uint16_t MAX_HEADER_SIZE = sizeof(uint16_t);
    constexpr static uint16_t MAX_PAYLOAD_SIZE = MAX_NODE_SIZE - MAX_HEADER_SIZE;

    explicit BaseNode(uint16_t payload_len);
    explicit BaseNode(const std::byte payload_data[], uint16_t payload_size); // 反序列化构造函数
    explicit BaseNode(const SerializedData& serialized_data); // 反序列化构造函数

    // 复制控制
    BaseNode(const BaseNode& other);
    BaseNode& operator=(const BaseNode& other);
    BaseNode(BaseNode&& other) noexcept;
    BaseNode& operator=(BaseNode&& other) noexcept;

    [[nodiscard]] virtual SerializedData serialize() const;
    [[nodiscard]] static BaseNode deserialize(const std::byte data[], uint16_t size);

    [[nodiscard]] virtual const std::byte* getNodePayloadPointer() const noexcept;
    [[nodiscard]] virtual uint16_t getNodePayloadSize() const noexcept;
    [[nodiscard]] virtual uint16_t getNodeFullSize() const noexcept;

    virtual void setPayload(const std::byte* data, uint16_t size);

    friend std::ostream& operator<<(std::ostream& os, const BaseNode& node);

    virtual void clear() noexcept;
    virtual ~BaseNode() = default;

protected:
    uint16_t m_payload_len { 0 }; // Payload长度
    std::unique_ptr<std::byte[]> m_payload; // 实际的Payload数据
};

#endif // BASENODE_H
